<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD><TITLE>expr manual page - Tcl Built-In Commands</TITLE>
<link rel="stylesheet" href="../docs.css" type="text/css" media="all">
</HEAD>
<BODY><H2><a href="../contents.htm">Tcl8.6.11/Tk8.6.11 Documentation</a> <small>&gt;</small> <a href="contents.htm">Tcl Commands</a> <small>&gt;</small> expr</H2>
<H3><A HREF="../UserCmd/contents.htm">Tcl/Tk Applications</A> | <A HREF="../TclCmd/contents.htm">Tcl Commands</A> | <A HREF="../TkCmd/contents.htm">Tk Commands</A> | <A HREF="../ItclCmd/contents.htm">[incr Tcl] Package Commands</A> | <A HREF="../SqliteCmd/contents.htm">SQLite3 Package Commands</A> | <A HREF="../TdbcCmd/contents.htm">TDBC Package Commands</A> | <A HREF="../TdbcmysqlCmd/contents.htm">tdbc::mysql Package Commands</A> | <A HREF="../TdbcodbcCmd/contents.htm">tdbc::odbc Package Commands</A> | <A HREF="../TdbcpostgresCmd/contents.htm">tdbc::postgres Package Commands</A> | <A HREF="../TdbcsqliteCmd/contents.htm">tdbc::sqlite3 Package Commands</A> | <A HREF="../ThreadCmd/contents.htm">Thread Package Commands</A> | <A HREF="../TclLib/contents.htm">Tcl C API</A> | <A HREF="../TkLib/contents.htm">Tk C API</A> | <A HREF="../ItclLib/contents.htm">[incr Tcl] Package C API</A> | <A HREF="../TdbcLib/contents.htm">TDBC Package C API</A></H3>
<DL>
<DD><A HREF="expr.htm#M2" NAME="L467">NAME</A>
<DL><DD>expr &mdash; Evaluate an expression</DD></DL>
<DD><A HREF="expr.htm#M3" NAME="L468">SYNOPSIS</A>
<DL>
</DL>
<DD><A HREF="expr.htm#M4" NAME="L469">DESCRIPTION</A>
<DD><A HREF="expr.htm#M5" NAME="L470">OPERANDS</A>
<OL class="operands">
</OL>
<DD><A HREF="expr.htm#M6" NAME="L471">OPERATORS</A>
<DL class="operators">
<DD><A HREF="expr.htm#M7" NAME="L472"><B>-  +  ~  !</B></A>
<DD><A HREF="expr.htm#M8" NAME="L473"><B>**</B></A>
<DD><A HREF="expr.htm#M9" NAME="L474"><B>*  /  %</B></A>
<DD><A HREF="expr.htm#M10" NAME="L475"><B>+  -</B></A>
<DD><A HREF="expr.htm#M11" NAME="L476"><B>&lt;&lt;  &gt;&gt;</B></A>
<DD><A HREF="expr.htm#M12" NAME="L477"><B>&lt;  &gt;  &lt;=  &gt;=</B></A>
<DD><A HREF="expr.htm#M13" NAME="L478"><B>==  !=</B></A>
<DD><A HREF="expr.htm#M14" NAME="L479"><B>eq  ne</B></A>
<DD><A HREF="expr.htm#M15" NAME="L480"><B>in  ni</B></A>
<DD><A HREF="expr.htm#M16" NAME="L481"><B>&amp;</B></A>
<DD><A HREF="expr.htm#M17" NAME="L482"><B>^</B></A>
<DD><A HREF="expr.htm#M18" NAME="L483"><B>|</B></A>
<DD><A HREF="expr.htm#M19" NAME="L484"><B>&amp;&amp;</B></A>
<DD><A HREF="expr.htm#M20" NAME="L485"><B>||</B></A>
<DD><A HREF="expr.htm#M21" NAME="L486"><I>x </I><B>?</B><I> y </I><B>:</B><I> z</I></A>
</DL>
<DD><A HREF="expr.htm#M22" NAME="L487">MATH FUNCTIONS</A>
<DD><A HREF="expr.htm#M23" NAME="L488">TYPES, OVERFLOW, AND PRECISION</A>
<DD><A HREF="expr.htm#M24" NAME="L489">STRING OPERATIONS</A>
<DD><A HREF="expr.htm#M25" NAME="L490">PERFORMANCE CONSIDERATIONS</A>
<DD><A HREF="expr.htm#M26" NAME="L491">EXAMPLES</A>
<DD><A HREF="expr.htm#M27" NAME="L492">SEE ALSO</A>
<DD><A HREF="expr.htm#M28" NAME="L493">KEYWORDS</A>
<DD><A HREF="expr.htm#M29" NAME="L494">COPYRIGHT</A>
</DL>
<H3><A NAME="M2">NAME</A></H3>
expr &mdash; Evaluate an expression
<H3><A NAME="M3">SYNOPSIS</A></H3>
<B>expr </B><I>arg </I>?<I>arg arg ...</I>?<BR>
<H3><A NAME="M4">DESCRIPTION</A></H3>
Concatenates <I>arg</I>s (adding separator spaces between them),
evaluates the result as a Tcl expression, and returns the value.
The operators permitted in Tcl expressions include a subset of
the operators permitted in C expressions.  For those operators
common to both Tcl and C, Tcl applies the same meaning and precedence
as the corresponding C operators.
Expressions almost always yield numeric results
(integer or floating-point values).
For example, the expression
<P>
<PRE><B>expr</B> 8.2 + 6</PRE>
<P>
evaluates to 14.2.
Tcl expressions differ from C expressions in the way that
operands are specified.  Also, Tcl expressions support
non-numeric operands and string comparisons, as well as some
additional operators not found in C.
<H4><A NAME="M5">OPERANDS</A></H4>
A Tcl expression consists of a combination of operands, operators,
parentheses and commas.
White space may be used between the operands and operators and
parentheses (or commas); it is ignored by the expression's instructions.
Where possible, operands are interpreted as integer values.
Integer values may be specified in decimal (the normal case), in binary
(if the first two characters of the operand are <B>0b</B>), in octal
(if the first two characters of the operand are <B>0o</B>), or in hexadecimal
(if the first two characters of the operand are <B>0x</B>).  For
compatibility with older Tcl releases, an octal integer value is also
indicated simply when the first character of the operand is <B>0</B>,
whether or not the second character is also <B>o</B>.
If an operand does not have one of the integer formats given
above, then it is treated as a floating-point number if that is
possible.  Floating-point numbers may be specified in any of several
common formats making use of the decimal digits, the decimal point <B>.</B>,
the characters <B>e</B> or <B>E</B> indicating scientific notation, and
the sign characters <B>+</B> or <B>-</B>.  For example, all of the
following are valid floating-point numbers:  2.1, 3., 6e4, 7.91e+16.
Also recognized as floating point values are the strings <B>Inf</B>
and <B>NaN</B> making use of any case for each character.
If no numeric interpretation is possible (note that all literal
operands that are not numeric or boolean must be quoted with either
braces or with double quotes), then an operand is left as a string
(and only a limited set of operators may be applied to it).
<P>
Operands may be specified in any of the following ways:
<P>
<OL class="operands">
<LI value="1">
As a numeric value, either integer or floating-point.
<P><LI value="2">
As a boolean value, using any form understood by <B><A HREF="../TclCmd/string.htm">string is</A></B>
<B>boolean</B>.
<P><LI value="3">
As a Tcl variable, using standard <B>$</B> notation.
The variable's value will be used as the operand.
<P><LI value="4">
As a string enclosed in double-quotes.
The expression parser will perform backslash, variable, and
command substitutions on the information between the quotes,
and use the resulting value as the operand
<P><LI value="5">
As a string enclosed in braces.
The characters between the open brace and matching close brace
will be used as the operand without any substitutions.
<P><LI value="6">
As a Tcl command enclosed in brackets.
The command will be executed and its result will be used as
the operand.
<P><LI value="7">
As a mathematical function whose arguments have any of the above
forms for operands, such as <B>sin($x)</B>.  See <B><A HREF="#M22">MATH FUNCTIONS</A></B> below for
a discussion of how mathematical functions are handled.
<P></OL>
<P>
Where the above substitutions occur (e.g. inside quoted strings), they
are performed by the expression's instructions.
However, the command parser may already have performed one round of
substitution before the expression processor was called.
As discussed below, it is usually best to enclose expressions
in braces to prevent the command parser from performing substitutions
on the contents.
<P>
For some examples of simple expressions, suppose the variable
<B>a</B> has the value 3 and
the variable <B>b</B> has the value 6.
Then the command on the left side of each of the lines below
will produce the value on the right side of the line:
<P>
<PRE><B>expr</B> {3.1 + $a}	<I>6.1</I>
<B>expr</B> {2 + &quot;$a.$b&quot;}	<I>5.6</I>
<B>expr</B> {4*[llength &quot;6 2&quot;]}	<I>8</I>
<B>expr</B> {{word one} &lt; &quot;word $a&quot;}	<I>0</I></PRE>
<H4><A NAME="M6">OPERATORS</A></H4>
The valid operators (most of which are also available as commands in
the <B>tcl::mathop</B> namespace; see the <B><A HREF="../TclCmd/mathop.htm">mathop</A></B>(n) manual page
for details) are listed below, grouped in decreasing order of precedence:
<P>
<DL class="operators">
<DT><A NAME="M7"><B>-  +  ~  !</B></A><DD>
Unary minus, unary plus, bit-wise NOT, logical NOT.  None of these operators
may be applied to string operands, and bit-wise NOT may be
applied only to integers.
<P><DT><A NAME="M8"><B>**</B></A><DD>
Exponentiation.  Valid for any numeric operands.  The maximum exponent value
that Tcl can handle if the first number is an integer &gt; 1 is 268435455.
<P><DT><A NAME="M9"><B>*  /  %</B></A><DD>
Multiply, divide, remainder.  None of these operators may be
applied to string operands, and remainder may be applied only
to integers.
The remainder will always have the same sign as the divisor and
an absolute value smaller than the absolute value of the divisor.
<P>
When applied to integers, the division and remainder operators can be
considered to partition the number line into a sequence of equal-sized
adjacent non-overlapping pieces where each piece is the size of the divisor;
the division result identifies which piece the divisor lay within, and the
remainder result identifies where within that piece the divisor lay. A
consequence of this is that the result of
&ldquo;-57 <B>/</B> 10&rdquo;
is always -6, and the result of
&ldquo;-57 <B>%</B> 10&rdquo;
is always 3.
<P><DT><A NAME="M10"><B>+  -</B></A><DD>
Add and subtract.  Valid for any numeric operands.
<P><DT><A NAME="M11"><B>&lt;&lt;  &gt;&gt;</B></A><DD>
Left and right shift.  Valid for integer operands only.
A right shift always propagates the sign bit.
<P><DT><A NAME="M12"><B>&lt;  &gt;  &lt;=  &gt;=</B></A><DD>
Boolean less, greater, less than or equal, and greater than or equal.
Each operator produces 1 if the condition is true, 0 otherwise.
These operators may be applied to strings as well as numeric operands,
in which case string comparison is used.
<P><DT><A NAME="M13"><B>==  !=</B></A><DD>
Boolean equal and not equal.  Each operator produces a zero/one result.
Valid for all operand types.
<P><DT><A NAME="M14"><B>eq  ne</B></A><DD>
Boolean string equal and string not equal.  Each operator produces a
zero/one result.  The operand types are interpreted only as strings.
<P><DT><A NAME="M15"><B>in  ni</B></A><DD>
List containment and negated list containment.  Each operator produces
a zero/one result and treats its first argument as a string and its
second argument as a Tcl list.  The <B>in</B> operator indicates
whether the first argument is a member of the second argument list;
the <B>ni</B> operator inverts the sense of the result.
<P><DT><A NAME="M16"><B>&amp;</B></A><DD>
Bit-wise AND.  Valid for integer operands only.
<P><DT><A NAME="M17"><B>^</B></A><DD>
Bit-wise exclusive OR.  Valid for integer operands only.
<P><DT><A NAME="M18"><B>|</B></A><DD>
Bit-wise OR.  Valid for integer operands only.
<P><DT><A NAME="M19"><B>&amp;&amp;</B></A><DD>
Logical AND.  Produces a 1 result if both operands are non-zero,
0 otherwise.
Valid for boolean and numeric (integers or floating-point) operands only.
This operator evaluates lazily; it only evaluates its second operand if it
must in order to determine its result.
<P><DT><A NAME="M20"><B>||</B></A><DD>
Logical OR.  Produces a 0 result if both operands are zero, 1 otherwise.
Valid for boolean and numeric (integers or floating-point) operands only.
This operator evaluates lazily; it only evaluates its second operand if it
must in order to determine its result.
<P><DT><A NAME="M21"><I>x </I><B>?</B><I> y </I><B>:</B><I> z</I></A><DD>
If-then-else, as in C.  If <I>x</I>
evaluates to non-zero, then the result is the value of <I>y</I>.
Otherwise the result is the value of <I>z</I>.
The <I>x</I> operand must have a boolean or numeric value.
This operator evaluates lazily; it evaluates only one of <I>y</I> or <I>z</I>.
<P></DL>
<P>
See the C manual for more details on the results
produced by each operator.
The exponentiation operator promotes types like the multiply and
divide operators, and produces a result that is the same as the output
of the <B>pow</B> function (after any type conversions.)
All of the binary operators but exponentiation group left-to-right
within the same precedence level; exponentiation groups right-to-left.  For example, the command
<P>
<P>
<PRE><B>expr</B> {4*2 &lt; 7}</PRE>
<P>
returns 0, while
<P>
<PRE><B>expr</B> {2**3**2}</PRE>
<P>
returns 512.
<P>
The <B>&amp;&amp;</B>, <B>||</B>, and <B>?:</B> operators have
&ldquo;lazy evaluation&rdquo;,
just as in C, which means that operands are not evaluated if they are
not needed to determine the outcome.  For example, in the command
<P>
<PRE><B>expr</B> {$v?[a]:[b]}</PRE>
<P>
only one of
&ldquo;<B>[a]</B>&rdquo;
or
&ldquo;<B>[b]</B>&rdquo;
will actually be evaluated,
depending on the value of <B>$v</B>.  Note, however, that this is
only true if the entire expression is enclosed in braces;  otherwise
the Tcl parser will evaluate both
&ldquo;<B>[a]</B>&rdquo;
and
&ldquo;<B>[b]</B>&rdquo;
before invoking the <B>expr</B> command.
<H4><A NAME="M22">MATH FUNCTIONS</A></H4>
When the expression parser encounters a mathematical function
such as <B>sin($x)</B>, it replaces it with a call to an ordinary
Tcl command in the <B>tcl::mathfunc</B> namespace.  The processing
of an expression such as:
<P>
<PRE><B>expr</B> {sin($x+$y)}</PRE>
<P>
is the same in every way as the processing of:
<P>
<PRE><B>expr</B> {[tcl::mathfunc::sin [<B>expr</B> {$x+$y}]]}</PRE>
<P>
which in turn is the same as the processing of:
<P>
<PRE>tcl::mathfunc::sin [<B>expr</B> {$x+$y}]</PRE>
<P>
The executor will search for <B>tcl::mathfunc::sin</B> using the usual
rules for resolving functions in namespaces. Either
<B>::tcl::mathfunc::sin</B> or <B>[namespace
current]::tcl::mathfunc::sin</B> will satisfy the request, and others
may as well (depending on the current <B><A HREF="../TclCmd/namespace.htm">namespace path</A></B> setting).
<P>
Some mathematical functions have several arguments, separated by commas like in C. Thus:
<P>
<PRE><B>expr</B> {hypot($x,$y)}</PRE>
<P>
ends up as
<P>
<PRE>tcl::mathfunc::hypot $x $y</PRE>
<P>
See the <B><A HREF="../TclCmd/mathfunc.htm">mathfunc</A></B>(n) manual page for the math functions that are
available by default.
<H4><A NAME="M23">TYPES, OVERFLOW, AND PRECISION</A></H4>
All internal computations involving integers are done calling on the
LibTomMath multiple precision integer library as required so that all
integer calculations are performed exactly.  Note that in Tcl releases
prior to 8.5, integer calculations were performed with one of the C types
<I>long int</I> or <I><A HREF="../TclLib/IntObj.htm">Tcl_WideInt</A></I>, causing implicit range truncation
in those calculations where values overflowed the range of those types.
Any code that relied on these implicit truncations will need to explicitly
add <B><A HREF="../TclCmd/mathfunc.htm">int()</A></B> or <B><A HREF="../TclCmd/mathfunc.htm">wide()</A></B> function calls to expressions at the points
where such truncation is required to take place.
<P>
All internal computations involving floating-point are
done with the C type <I>double</I>.
When converting a string to floating-point, exponent overflow is
detected and results in the <I>double</I> value of <B>Inf</B> or
<B>-Inf</B> as appropriate.  Floating-point overflow and underflow
are detected to the degree supported by the hardware, which is generally
pretty reliable.
<P>
Conversion among internal representations for integer, floating-point,
and string operands is done automatically as needed.
For arithmetic computations, integers are used until some
floating-point number is introduced, after which floating-point is used.
For example,
<P>
<PRE><B>expr</B> {5 / 4}</PRE>
<P>
returns 1, while
<P>
<PRE><B>expr</B> {5 / 4.0}
<B>expr</B> {5 / ( [string length &quot;abcd&quot;] + 0.0 )}</PRE>
<P>
both return 1.25.
Floating-point values are always returned with a
&ldquo;<B>.</B>&rdquo;
or an
&ldquo;<B>e</B>&rdquo;
so that they will not look like integer values.  For example,
<P>
<PRE><B>expr</B> {20.0/5.0}</PRE>
<P>
returns <B>4.0</B>, not <B>4</B>.
<H4><A NAME="M24">STRING OPERATIONS</A></H4>
String values may be used as operands of the comparison operators,
although the expression evaluator tries to do comparisons as integer
or floating-point when it can,
i.e., when all arguments to the operator allow numeric interpretations,
except in the case of the <B>eq</B> and <B>ne</B> operators.
If one of the operands of a comparison is a string and the other
has a numeric value, a canonical string representation of the numeric
operand value is generated to compare with the string operand.
Canonical string representation for integer values is a decimal string
format.  Canonical string representation for floating-point values
is that produced by the <B>%g</B> format specifier of Tcl's
<B><A HREF="../TclCmd/format.htm">format</A></B> command.  For example, the commands
<P>
<PRE><B>expr</B> {&quot;0x03&quot; &gt; &quot;2&quot;}
<B>expr</B> {&quot;0y&quot; &gt; &quot;0x12&quot;}</PRE>
<P>
both return 1.  The first comparison is done using integer
comparison, and the second is done using string comparison.
Because of Tcl's tendency to treat values as numbers whenever
possible, it is not generally a good idea to use operators like <B>==</B>
when you really want string comparison and the values of the
operands could be arbitrary;  it is better in these cases to use
the <B>eq</B> or <B>ne</B> operators, or the <B><A HREF="../TclCmd/string.htm">string</A></B> command instead.
<H3><A NAME="M25">PERFORMANCE CONSIDERATIONS</A></H3>
Enclose expressions in braces for the best speed and the smallest
storage requirements.
This allows the Tcl bytecode compiler to generate the best code.
<P>
As mentioned above, expressions are substituted twice:
once by the Tcl parser and once by the <B>expr</B> command.
For example, the commands
<P>
<PRE>set a 3
set b {$a + 2}
<B>expr</B> $b*4</PRE>
<P>
return 11, not a multiple of 4.
This is because the Tcl parser will first substitute
&ldquo;<B>$a + 2</B>&rdquo;
for the variable <B>b</B>,
then the <B>expr</B> command will evaluate the expression
&ldquo;<B>$a + 2*4</B>&rdquo;.
<P>
Most expressions do not require a second round of substitutions.
Either they are enclosed in braces or, if not,
their variable and command substitutions yield numbers or strings
that do not themselves require substitutions.
However, because a few unbraced expressions
need two rounds of substitutions,
the bytecode compiler must emit
additional instructions to handle this situation.
The most expensive code is required for
unbraced expressions that contain command substitutions.
These expressions must be implemented by generating new code
each time the expression is executed.
<P>
If it is necessary to include a non-constant expression string within the
wider context of an otherwise-constant expression, the most efficient
technique is to put the varying part inside a recursive <B>expr</B>, as this at
least allows for the compilation of the outer part, though it does mean that
the varying part must itself be evaluated as a separate expression. Thus, in
this example the result is 20 and the outer expression benefits from fully
cached bytecode compilation.
<P>
<PRE>set a 3
set b {$a + 2}
<B>expr</B> {[<B>expr</B> $b] * 4}</PRE>
<P>
When the expression is unbraced to allow the substitution of a function or
operator, consider using the commands documented in the <B><A HREF="../TclCmd/mathfunc.htm">mathfunc</A></B>(n) or
<B><A HREF="../TclCmd/mathop.htm">mathop</A></B>(n) manual pages directly instead.
<H3><A NAME="M26">EXAMPLES</A></H3>
Define a procedure that computes an
&ldquo;interesting&rdquo;
mathematical function:
<P>
<PRE>proc tcl::mathfunc::calc {x y} {
    <B>expr</B> { ($x**2 - $y**2) / exp($x**2 + $y**2) }
}</PRE>
<P>
Convert polar coordinates into cartesian coordinates:
<P>
<PRE># convert from ($radius,$angle)
set x [<B>expr</B> { $radius * cos($angle) }]
set y [<B>expr</B> { $radius * sin($angle) }]</PRE>
<P>
Convert cartesian coordinates into polar coordinates:
<P>
<PRE># convert from ($x,$y)
set radius [<B>expr</B> { hypot($y, $x) }]
set angle  [<B>expr</B> { atan2($y, $x) }]</PRE>
<P>
Print a message describing the relationship of two string values to
each other:
<P>
<PRE>puts &quot;a and b are [<B>expr</B> {$a eq $b ? {equal} : {different}}]&quot;</PRE>
<P>
Set a variable to whether an environment variable is both defined at
all and also set to a true boolean value:
<P>
<PRE>set isTrue [<B>expr</B> {
    [info exists ::env(SOME_ENV_VAR)] &amp;&amp;
    [string is true -strict $::env(SOME_ENV_VAR)]
}]</PRE>
<P>
Generate a random integer in the range 0..99 inclusive:
<P>
<PRE>set randNum [<B>expr</B> { int(100 * rand()) }]</PRE>
<H3><A NAME="M27">SEE ALSO</A></H3>
<B><A HREF="../TclCmd/array.htm">array</A></B>, <B><A HREF="../TclCmd/for.htm">for</A></B>, <B><A HREF="../TclCmd/if.htm">if</A></B>, <B><A HREF="../TclCmd/mathfunc.htm">mathfunc</A></B>, <B><A HREF="../TclCmd/mathop.htm">mathop</A></B>, <B><A HREF="../TclCmd/namespace.htm">namespace</A></B>, <B><A HREF="../TclCmd/proc.htm">proc</A></B>, <B><A HREF="../TclCmd/string.htm">string</A></B>, <B><A HREF="../TclCmd/Tcl.htm">Tcl</A></B>, <B><A HREF="../TclCmd/while.htm">while</A></B>
<H3><A NAME="M28">KEYWORDS</A></H3>
<A href="../Keywords/A.htm#arithmetic">arithmetic</A>, <A href="../Keywords/B.htm#boolean">boolean</A>, <A href="../Keywords/C.htm#compare">compare</A>, <A href="../Keywords/E.htm#expression">expression</A>, <A href="../Keywords/F.htm#fuzzy comparison">fuzzy comparison</A>
<H3><A NAME="M29">COPYRIGHT</A></H3>
Copyright &copy; 1993 The Regents of the University of California.<BR>
Copyright &copy; 1994-2000 Sun Microsystems Incorporated.<BR>
Copyright &copy; 2005 Kevin B. Kenny &lt;kennykb@acm.org&gt;. All rights reserved.<BR>
<div class="copy">Copyright &copy; 1993 The Regents of the University of California.
<BR>Copyright &copy; 1994-2000 Sun Microsystems, Inc.
<BR>Copyright &copy; 2005 Kevin B. Kenny &lt;kennykb(at)acm.org&gt;. All rights reserved
</div>
</BODY></HTML>
